package study.Utils.Security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 *
 * @author Ychiha
 * @version 1.0
 * @date 11/1/2022 上午9:42
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder pw;

    //测试用的账号(实际项目用数据库验证验证处理)
    private final String matchUsername = "ychiha";
    //测试用的密码(实际项目用数据库数据验证处理)
    private final String matchPassword = "123456";

    /**
     * 在web端，提交的用户信息必须为username，否则报错
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        System.out.println("执行了加载方法");

        //1、查询数据库判断用户名是否存在，不存在将抛出异常UsernameNotFoundException异常
        if(!matchUsername.equals(username)){
            throw new UsernameNotFoundException("用户名不存在");
        }

        //2、如果存在该用户-把查询出来的密码(注册时已经加密过的)进行解析，或者直接把密码放入构造方法
        String password = pw.encode(matchPassword);

        //返回Security的User(用户名、密码、权限[该方法以","进行分割形成List，此处赋予管理员和普通用户的权限])
//        return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal"));
        //角色(必须以"ROLE_"作为前缀):
        return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("normal,Vip,ROLE_yzm,/yzm.html"));
    }
}
